﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace SSHTunnel {
    public partial class Form1 : Form {
        private static BlueSSH _blueSSH = new BlueSSH();
        private static AccountInfo _accountInfo = BlueSSH.Account;
        private static Process _process;
        private static int _porcessID = -1000;
        private static Timer _timer;
        private static Timer _countTimer;
        private static TimeSpan _timeSpan;
        private static string _picSavePath = @"D:\BlueSSH_PWD";

        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            if (string.IsNullOrEmpty(textBox_Password.Text)) {
                MessageBox.Show("输入图片中的字符");
            }
            else {
                SwapFunc();
            }
        }

        private void SwapFunc() {
            if (button1.Text.Equals("断开")) {
                button1.Text = "连接";
                KillProcess();
            }
            else if (button1.Text.Equals("连接")) {
                button1.Text = "断开";
                Connect();
            }
        }

        /// <summary>
        ///  plink.exe "free.bluessh.com" -N -Z bluessh -P 21 -l bluessh -D 7070 -v
        ///  
        /// -N bluessh@free.bluessh.com -P 21 -D 127.0.0.1:7070 -pw 65e84b -Z bluessh -v
        /// </summary>
        private void Connect() {
            _process = new Process();
            ProcessStartInfo info = new ProcessStartInfo();
            string arguments = "-N " + textBox_User.Text + "@" + textBox_Host.Text + " -P " + textBox_RPort.Text + " -D 127.0.0.1:" + textBox_LPort.Text + " -pw " + textBox_Password.Text + " -Z " + textBox_User.Text + " -v";
            info.FileName = AppDomain.CurrentDomain.BaseDirectory + "/plonk.exe";
            info.Arguments = arguments;
            info.CreateNoWindow = true;
            info.UseShellExecute = false;
            info.RedirectStandardInput = true;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;

            _process.StartInfo = info;
            _process.OutputDataReceived += new DataReceivedEventHandler(PrintMessage);
            _process.ErrorDataReceived += new DataReceivedEventHandler(PrintMessage);
            _process.Start();
            _porcessID = _process.Id;

            _process.StandardInput.AutoFlush = true;
            _process.StandardInput.Write('y');
            _process.BeginOutputReadLine();
            _process.BeginErrorReadLine();
        }

        private void PrintMessage(object sender, DataReceivedEventArgs e) {
            this.textBox2.Invoke(new MethodInvoker(() => {
                textBox2.ScrollToCaret();
                textBox2.AppendText("[" + DateTime.Now.ToString("HH:mm.ss") + "] " + e.Data + "\r\n");
            }));
        }

        private void RefreshAccount(object sender, EventArgs e) {
            _timer.Stop();
            _countTimer.Stop();
            button1.Text = "连接";

            KillProcess();

            do {
                _blueSSH.Refresh();
            } while (_accountInfo.Time.Subtract(DateTime.Now).TotalMinutes < 5);

            _timeSpan = _accountInfo.Time.Subtract(DateTime.Now);
            _timer.Interval = (int)_timeSpan.TotalMilliseconds;
            _timer.Start();
            _countTimer.Start();

            this.Invoke(new MethodInvoker(() => {
                pictureBox1.Image = _accountInfo.Img;
                textBox_Host.Text = _accountInfo.Host;
                textBox_RPort.Text = _accountInfo.Port;

                textBox_Minutes.Text = _timeSpan.Minutes.ToString();
                textBox_Seconds.Text = _timeSpan.Seconds.ToString();

                if (!Directory.Exists(_picSavePath)) {
                    Directory.CreateDirectory(_picSavePath);
                }
                _accountInfo.Img.Save(Path.Combine(_picSavePath, Guid.NewGuid().ToString() + ".png"));
            }));

            MessageBox.Show("密码已更改，请重新连接~");
        }

        private void button2_Click(object sender, EventArgs e) {
            KillProcess();
            this.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e) {
            this.Invoke(new MethodInvoker(() => {
                tabControl1.SelectedIndex = 1;
                _blueSSH.Refresh();

                _countTimer = new Timer();
                _countTimer.Interval = 1000;
                _countTimer.Tick += new EventHandler(RefreshTime);
                _countTimer.Start();

                _timeSpan = _accountInfo.Time.Subtract(DateTime.Now);
                _timer = new Timer();
                _timer.Interval = (int)_timeSpan.TotalMilliseconds;
                _timer.Tick += new EventHandler(RefreshAccount);
                _timer.Start();

                pictureBox1.Image = _accountInfo.Img;
                textBox_Host.Text = _accountInfo.Host;
                textBox_User.Text = _accountInfo.UserName;

                if (!Directory.Exists(_picSavePath)) {
                    Directory.CreateDirectory(_picSavePath);
                }
                _accountInfo.Img.Save(Path.Combine(_picSavePath, Guid.NewGuid().ToString() + ".png"));

                int minutes = _timeSpan.Minutes;
                int seconds = _timeSpan.Seconds;
                textBox_Minutes.Text = minutes >= 10 ? minutes.ToString() : "0" + minutes;
                textBox_Seconds.Text = seconds >= 10 ? seconds.ToString() : "0" + seconds;
            }));
        }

        private void RefreshTime(object sender, EventArgs e) {
            _timeSpan = _timeSpan.Add(-(new TimeSpan(0, 0, 1)));
            this.Invoke(new MethodInvoker(() => {
                int minutes = _timeSpan.Minutes;
                int seconds = _timeSpan.Seconds;
                textBox_Minutes.Text = minutes >= 10 ? minutes.ToString() : "0" + minutes;
                textBox_Seconds.Text = seconds >= 10 ? seconds.ToString() : "0" + seconds;
            }));
        }

        private void button4_Click(object sender, EventArgs e) {
            this.Hide();
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) {
            if (e.Button == MouseButtons.Right) {
                notifyIcon1.ContextMenuStrip = contextMenuStrip1;
                contextMenuStrip1.Show(Cursor.Position.X + 10, Cursor.Position.Y - 10);
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e) {
            this.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) {
            KillProcess();
            this.Dispose();
        }

        private void KillProcess() {
            try {
                if (_porcessID > 0) {
                    Process process = Process.GetProcessById(_porcessID);
                    if (process != null) {
                        process.Kill();
                    }
                }
            }
            catch (Exception) {

            }
        }
    }
}
